<template>
  <div class="echarts_box">
    <div
      class="echarts_box"
      ref="echarts_box"
      :style="{ opacity: data.length == 0 ? '0' : '1' }"
    ></div>
    <!---------------------- 无数据是显示 ---------------------->
    <Nodata class="Nodata" v-show="data.length == 0"></Nodata>
  </div>
</template>

<script>
import { mapState, mapActions, mapGetters } from "vuex";
import fontSize from "@/modules/fontSize";
const elementResizeDetectorMaker = require("element-resize-detector");
export default {
  mounted() {},
  computed: {
    // ...mapGetters(["echartsColor"]),
  },
  watch: {
    itemWidth: "drawLine", // 数值变化是更新图表
    length: "drawLine", // 数值变化是更新图表
    showLabel: "drawLine", // 数值变化是更新图表
    img: "drawLine", // 数值变化是更新图表
    color: "drawLine", // 数值变化是更新图表
    data: "drawLine", // 数值变化是更新图表
    tooltipShow: "drawLine", // 数值变化是更新图表
  },
  props: {
    data: {
      // 返回的数据
      type: Array | Object,
      default: function () {
        return [];
      },
    },
    itemWidth: {
      type: Number | String,
      default: () => 1,
    },
    tooltipShow: {
      type: Boolean,
      default: true,
    },
    showLabel: {
      type: Boolean,
      default: false,
    },
    // itemHeight: {
    //   type: Number | String,
    //   default: () => 11,
    // },
    isLenged: {
      type: Boolean,
      default: () => true,
    },
    img: {
      // 图片地址
      type: Object | String,
      default: () => require("@/assets/img/index/circle.png"),
    },
    radius: {
      type: Array | String,
      default: () => ["70%", "75%"],
    },
    length: {
      type: String | Number,
      default: () => 100,
    },
    color: {
      type: Array,
      default: () => [],
    },
    //标题
    titleLabel: {
      type: String | Number,
      default: () => "总次数",
    },
    unit: {
      type: String | Number,
      default: () => "次",
    },
    allNum: {
      type: String | Number,
      default: () => "",
    },
  },
  mounted() {
    this.drawLine();
    let erd = elementResizeDetectorMaker();
    erd.listenTo(this.$refs.echarts_box, (ele) => {
      this.drawLine();
    });
  },
  methods: {
    drawLine() {
      try {
        var cw = document.body.clientWidth;
        // console.log(cw);
        this.$nextTick(() => {
          let colorList = [
            "#23c3ff",
            "#fc8738",
            "#ffda00",
            "#09cc3b",
            "#fc4ff0",
            "#6056e2",
            "rgba(35,195,255,1)",
            "rgba(0,235,205,1)",
            "rgba(0,193,59,1)",
            "rgba(254,111,55,1)",
            // "rgba(252,42,42,1)",
            "rgba(255,203,0,1)",
            "rgba(252,42,42,1)",
            "#EE6666",
            // "#5470C6",
            // "#73C0DE",
            // "#FAC657",
            // "#FC2A2A",
            "#5470C6",
            "#73C0DE",
            // "#FAC657",
            "#91CC75",
            "#EE6666",
            // "#5470C6",
            // "#73C0DE",
            "#FAC657",
          ];
          colorList.unshift(...this.color);

          // var h = this.$refs.echarts_box.offsetHeight / 20;
          var _this = this;
          var myChart = _this.$echarts.init(_this.$refs.echarts_box);
          const data = [];
          var names = [];
          var values = [];
          let myData = [];
          myData = this.data;
          // if (myData.length > this.length) {
          //   myData = myData.splice(0, this.length);
          // }
          let titleNum = 0;
          for (var i = 0; i < myData.length; i++) {
            names.push(myData[i].name);
            values.push(myData[i].value);
            if (this.allNum != "") {
              titleNum += myData[i].value;
            } else {
              titleNum = this.allNum;
            }
            if (this.showLabel == false) {
              data.push({
                value: myData[i].value,
                name: myData[i].name,
              });
            } else {
              data.push({
                value: myData[i].value,
                name: myData[i].name,
              });
            }
          }
          titleNum = Number(titleNum).toFixed(0);
          var seriesOption = [
            {
              name: "",
              type: "pie",
              clockWise: false,
              radius: [
                fontSize.fontSize(0.415) * this.itemWidth,
                fontSize.fontSize(0.45) * this.itemWidth,
              ],
              width: fontSize.fontSize() * this.itemWidth, //自适应大小,
              height: fontSize.fontSize() * this.itemWidth, //自适应大小,
              hoverAnimation: false,
              center: ["50%", "50%"],
              left: "center",
              top: "center",
              // itemStyle: {
              //   normal: {
              //     label: {
              //       show: true,
              //     },
              //   },
              // },
              itemStyle: {
                normal: {
                  label: {
                    show: this.showLabel,
                    position: "outside",
                    fontSize: fontSize.fontSize(0.0845),
                    formatter: (params) => {
                      var percent = 0;
                      var total = 0;
                      for (var i = 0; i < this.data.length; i++) {
                        total += this.data[i].value;
                      }
                      percent = ((params.value / total) * 100).toFixed(0);
                      if (params.name !== "") {
                        return (
                          params.name +
                          percent +
                          "%" +
                          "\n" +
                          "\n" +
                          params.value +
                          "kw·h"
                        );
                      } else {
                        return "";
                      }
                    },
                  },
                  labelLine: {
                    length: 9,
                    length2: 4,
                    show: this.showLabel,
                    normal: {
                      lineStyle: {
                        color: "rgba(255, 255, 255, 0)",
                      },
                      smooth: 0.2,
                    },
                  },
                },
              },
              data: data,
            },
          ];

          let option = {
            // backgroundColor: "#0A2E5D",
            title: {
              show: true, //显示策略，默认值true,可选为：true（显示） | false（隐藏）
              text: this.allNum + this.unit, //主标题文本，'\n'指定换行
              subtext: this.titleLabel, //副标题文本，'\n'指定换行
              // link: "", //主标题文本超链接,默认值true
              // target: null, //指定窗口打开主标题超链接，支持'self' | 'blank'，不指定等同为'blank'（新窗口）
              x: "center", //水平安放位置，默认为'left'，可选为：'center' | 'left' | 'right' | {number}（x坐标，单位px）
              y: "38%", //垂直安放位置，默认为top，可选为：'top' | 'bottom' | 'center' | {number}（y坐标，单位px）
              // textAlign: "center", //水平对齐方式，默认根据x设置自动调整，可选为： left' | 'right' | 'center
              // backgroundColor: "rgba(0,218,218,0.3)", //标题背景颜色，默认'rgba(0,0,0,0)'透明
              // borderColor: "#ccc", //标题边框颜色,默认'#ccc'
              // borderWidth: 0, //标题边框线宽，单位px，默认为0（无边框）
              // padding: [5, 13, 5, 13], //标题内边距，单位px，默认各方向内边距为5，接受数组分别设定上右下左边距
              itemGap: 5, //主副标题纵向间隔，单位px，默认为10
              textStyle: {
                //主标题文本样式{"fontSize": 18,"fontWeight": "bolder","color": "#333"}
                // fontFamily: "Arial, Verdana, sans...",
                fontSize: fontSize.fontSize(0.11),
                // fontStyle: "normal",
                fontWeight: "700",
                color: "#23c3ff",
                // textShadowColor: "rgba(0,255,211,1)", //阴影颜色
                // textShadowBlur: "10", //阴影的宽度
                // textShadowOffsetX: "-1", //阴影向X偏移
                // textShadowOffsetY: "-1", //阴影向Y偏移
              },
              subtextStyle: {
                //副标题文本样式{"color": "#aaa"}
                // fontFamily: "Arial, Verdana, sans...",
                // fontSize: 12,
                // fontStyle: "normal",
                // fontWeight: "normal",
                position: {
                  top: -30,
                },
                color: "rgba(255,255,255,1)",
                fontSize: fontSize.fontSize(0.07),
              },
            },
            color: colorList,
            graphic: {
              elements: [
                {
                  type: "image",
                  z: 0,
                  style: {
                    image: this.img,
                    width: fontSize.fontSize() * 1.17 * this.itemWidth, //自适应大小,
                    height: fontSize.fontSize() * 1.17 * this.itemWidth, //自适应大小,
                  },
                  left: "center",
                  top: "center",
                },
              ],
            },
            tooltip: {
              show: this.tooltipShow,
              trigger: "item",
              // formatter: function (params) {
              //   return 1111;
              // },
              formatter: "{b} : {c} ({d}%)",
            },
            // toolbox: {
            //   show: true,
            // },
            series: seriesOption,
          };
          myChart.setOption(option);
          /* 大小自适应 */
          window.addEventListener("resize", () => {
            // h = this.$refs.echarts_box.offsetHeight;
            // console.log(h);
            myChart.resize();
          });
          myChart.resize();
        });
      } catch (e) {
        console.log(e);
        // 错误处理代码片段
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.echarts_box {
  width: 100%;
  height: 100%;
  position: relative;
  .Nodata {
    position: absolute;
    top: 0;
    z-index: 10;
  }
}
</style>
